/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sack.picasawebalbums;

import com.google.gdata.client.GoogleService.InvalidCredentialsException;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.net.SocketException;
import java.util.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreeSelectionModel;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.Utilities;



/**
 * Top component which displays something.
 */
final class PicasaAlbumTopComponent extends TopComponent implements TreeSelectionListener,TreeExpansionListener {

    private static PicasaAlbumTopComponent instance;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "/org/sack/picasawebalbums/images/picasa16X16.png";
    private final String LoginFailed = "Error:\n1.Check Username/Password\n2.Check Internet Connection\nTry Again";
    private static final String PREFERRED_ID = "PicasaAlbumTopComponent";
    private static UserFeed myUserFeed;
    private static PicasawebService myService;
    private static String UserId ,Password;
    private DefaultMutableTreeNode root;
    private Feeds feed ;
    private List<AlbumEntry> albumList;

    File imageFile = null;
    private List<PhotoEntry> photoList;
    StyledDocument doc ;
    SlideShowThread ssThread;
    final static String path = java.lang.System.getProperty("user.home")+"/PicasaAlbums";
    private JTree jTree1;
    private ImageIcon photoIcon ;
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
    String photosize = "d";
    final String LINK_ATTRIBUTE = "linkact";
    boolean  authenticateflag = true;
    private PicasaAlbumTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(PicasaAlbumTopComponent.class, "CTL_PicasaAlbumTopComponent"));
        setToolTipText(NbBundle.getMessage(PicasaAlbumTopComponent.class, "HINT_PicasaAlbumTopComponent"));
        setIcon(Utilities.loadImage(ICON_PATH, true));
        jLabel4.setVisible(false);
        //for detecting clicks
	jTextPane1.addMouseListener(new TextClickListener());
	//for detecting motion
	jTextPane1.addMouseMotionListener(new TextMotionListener());
        Previous.setEnabled(false);
        Next.setEnabled(false);
    }
    private void UserAuthentication() {
         try {
            UserId = jTextField1.getText();
            Password = new String(jPasswordField1.getPassword());
            root = new DefaultMutableTreeNode("Albums");
            feed = new Feeds(UserId, Password);
            jTree1 = new JTree(root);
            jScrollPane1.setViewportView(jTree1);
            createNodes(root);
            jTree1.addTreeSelectionListener(this);
            File pathFolder = new File(path);
            if (!pathFolder.exists()) {
                pathFolder.mkdir();
            }
            jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            jTree1.addTreeExpansionListener(this);
            jPanel2.setVisible(false);
            authenticateflag = true;
        }catch(InvalidCredentialsException ex){
            JOptionPane.showMessageDialog(this, LoginFailed);
            authenticateflag = false;
        } 
        catch (AuthenticationException ex) {
            Exceptions.printStackTrace(ex);
            JOptionPane.showMessageDialog(this, LoginFailed);
            authenticateflag = false;
        }
         
    }
    private void checkButtons(DefaultMutableTreeNode node) {
        if(!node.isRoot() && ssThread==null){
            PlaySlideShow.setEnabled(true);
        }
        //Previous to be enabled or not
        if(node.getParent()!=null){
            if(node.getParent().getIndex(node)==0){
                Previous.setEnabled(false);
            }
            else{
            Previous.setEnabled(true);
            }
        }
        if(jTree1.getSelectionRows()[0]==jTree1.getRowCount()-1){
            Next.setEnabled(false);
        }
        else{
            Next.setEnabled(true);
        }
        if(node.getNextSibling()==null){
            Next.setEnabled(false);
        }
        if(node.isRoot()){
            Previous.setEnabled(false);
            Next.setEnabled(false);
        }
    }
    private void createNodes(DefaultMutableTreeNode root) {
        photoIcon = new ImageIcon("/org/sack/picasawebalbums/images/picasa8X8.png");
        jTree1.treeDidChange();
        myService = feed.getPicasawebService();
        if(myService!=null){
        myUserFeed = feed.getUserFeed();
        albumList = myUserFeed.getAlbumEntries();
        for(int i=0; i<albumList.size();i++){
            try {
                Album album = new Album(albumList.get(i).getName(), feed, albumList.get(i));
                DefaultMutableTreeNode AlbumNode = new DefaultMutableTreeNode(album);
                root.add(AlbumNode);
                //Check if there are photos for the album. If yes create the nodes.
                AlbumFeed myalbumfeed = feed.getAlbumFeed(album.AlbumName);
                if (!myalbumfeed.getPhotoEntries().isEmpty()) {
                    photoList = myalbumfeed.getPhotoEntries();
                    for (int j = 0; j < photoList.size(); j++) {
                        Photo photo = new Photo(photoList.get(j).getDescription().getPlainText(), feed, photoList.get(j), myalbumfeed);
                        AlbumNode.add(new DefaultMutableTreeNode(photo));
                        }
                    }
                } catch (SocketException ex) {
                    Exceptions.printStackTrace(ex);
                    JOptionPane.showMessageDialog(jTextPane1, "Check Your Internet Connection");
                }
            }
        }else{
         JOptionPane.showMessageDialog(jTextPane1,"Connection Failed!\nMake sure you are connected to the Net\nTry Again after the Connection is established","Connection Failed",0);
        }
    }
    void doAlbumProcess(Object selectedNode) {
        //type casting into Album
        Album album = (Album) selectedNode;
        imageFile = album.getAlbumImage(this);
        if(imageFile!=null){
            jTextPane1.setText("Loading... Please Wait");
            showImage(imageFile);
            showAlbumDetails(album);
            }
            else{
                JOptionPane.showMessageDialog(jTextPane1,"Album Not Found");
            }
        }
    void doPhotoProcess(Object selectedNode) {
        try {
            //type casting into Photo
            Photo photo = (Photo) selectedNode;
            imageFile = photo.getPhotoImage(this);
            if (imageFile != null) {
                showImage(imageFile);
            } else {
                JOptionPane.showMessageDialog(jTextPane1, "Photo Not Found\nPlease check your Internet Connection");
            }
        } catch (SocketException ex) {
            Exceptions.printStackTrace(ex);
            JOptionPane.showMessageDialog(jTextPane1, "Check Your Internet Connection");
        }
    }
    private void displayProcess() {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
        if(node==null){
            jTree1.setSelectionRow(jTree1.getLeadSelectionRow());
        }
        else{
            Object selectedNode = node.getUserObject();
            checkButtons(node);
        //is the node an album
        if(selectedNode instanceof Album){
            doAlbumProcess(selectedNode);
        }
        //is the node a photo
        if(selectedNode instanceof Photo){
            doPhotoProcess(selectedNode);
        }
    }
  }
  /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jToolBar1 = new javax.swing.JToolBar();
        Previous = new javax.swing.JButton();
        Next = new javax.swing.JButton();
        PlaySlideShow = new javax.swing.JButton();
        Stop = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        jPanel1.setBackground(new java.awt.Color(102, 102, 102));

        jSplitPane1.setBackground(new java.awt.Color(102, 102, 102));
        jSplitPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Picasaweb", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 0)));
        jSplitPane1.setDividerLocation(120);
        jSplitPane1.setDividerSize(2);
        jSplitPane1.setForeground(new java.awt.Color(255, 255, 255));

        jTextPane1.setBackground(new java.awt.Color(254, 254, 235));
        jTextPane1.setContentType("text/html");
        jTextPane1.setEditable(false);
        jTextPane1.setForeground(new java.awt.Color(255, 255, 0));
        jTextPane1.setText("<html>\r\n  <head>\r\n\r\n  </head>\r\n  <body>\r\n    <p style=\"margin-top: 0\">    </p>\r\n  </body>\r\n</html>\r\n");
        jScrollPane2.setViewportView(jTextPane1);

        jSplitPane1.setRightComponent(jScrollPane2);

        jScrollPane1.setBackground(new java.awt.Color(254, 254, 235));
        jSplitPane1.setLeftComponent(jScrollPane1);

        jToolBar1.setBackground(new java.awt.Color(102, 102, 102));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        Previous.setBackground(new java.awt.Color(102, 102, 102));
        Previous.setFont(new java.awt.Font("Tahoma", 1, 11));
        Previous.setForeground(new java.awt.Color(255, 255, 0));
        Previous.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/previous.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(Previous, "Previous");
        Previous.setToolTipText("Previous");
        Previous.setFocusable(false);
        Previous.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Previous.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Previous.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PreviousActionPerformed(evt);
            }
        });
        jToolBar1.add(Previous);

        Next.setBackground(new java.awt.Color(102, 102, 102));
        Next.setFont(new java.awt.Font("Tahoma", 1, 11));
        Next.setForeground(new java.awt.Color(255, 255, 0));
        Next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/next.png"))); // NOI18N
        Next.setMnemonic('N');
        org.openide.awt.Mnemonics.setLocalizedText(Next, "Next");
        Next.setToolTipText("Next");
        Next.setFocusable(false);
        Next.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Next.setVerifyInputWhenFocusTarget(false);
        Next.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NextActionPerformed(evt);
            }
        });
        jToolBar1.add(Next);

        PlaySlideShow.setBackground(new java.awt.Color(102, 102, 102));
        PlaySlideShow.setFont(new java.awt.Font("Tahoma", 1, 11));
        PlaySlideShow.setForeground(new java.awt.Color(255, 255, 0));
        PlaySlideShow.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/picasa24X24.png"))); // NOI18N
        PlaySlideShow.setMnemonic('S');
        org.openide.awt.Mnemonics.setLocalizedText(PlaySlideShow, "SlideShow");
        PlaySlideShow.setToolTipText("Play SlideShow");
        PlaySlideShow.setEnabled(false);
        PlaySlideShow.setFocusable(false);
        PlaySlideShow.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        PlaySlideShow.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/picasa32X32working.gif"))); // NOI18N
        PlaySlideShow.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        PlaySlideShow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PlaySlideShowActionPerformed(evt);
            }
        });
        jToolBar1.add(PlaySlideShow);

        Stop.setBackground(new java.awt.Color(102, 102, 102));
        Stop.setFont(new java.awt.Font("Tahoma", 1, 11));
        Stop.setForeground(new java.awt.Color(255, 255, 0));
        Stop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/stop.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(Stop, "Stop");
        Stop.setToolTipText("Stop");
        Stop.setEnabled(false);
        Stop.setFocusable(false);
        Stop.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Stop.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StopActionPerformed(evt);
            }
        });
        jToolBar1.add(Stop);

        jPanel3.setBackground(new java.awt.Color(102, 102, 102));
        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jPanel2.setBackground(new java.awt.Color(102, 102, 102));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Login", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 51)));

        jLabel1.setFont(new java.awt.Font("Lucida Sans", 1, 12));
        jLabel1.setForeground(new java.awt.Color(255, 255, 0));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/picasa32X32working.gif"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Google Username");

        jLabel2.setFont(new java.awt.Font("Lucida Sans", 1, 12));
        jLabel2.setForeground(new java.awt.Color(255, 255, 0));
        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Password");

        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyTyped(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, "Sign In");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPasswordField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 94, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton1))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2)
                    .add(jPasswordField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton1)
                    .add(jLabel1))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton2.setBackground(new java.awt.Color(102, 102, 102));
        jButton2.setFont(new java.awt.Font("Lucida Sans", 1, 12));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/picasa16X16.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jButton2, "Change User");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 131, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(19, 19, 19)
                        .add(jButton2))
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jToolBar1.add(jPanel3);

        jLabel4.setForeground(new java.awt.Color(255, 255, 0));
        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sack/picasawebalbums/images/picasa32X32working.gif"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "working...");

        jLabel3.setForeground(new java.awt.Color(255, 255, 0));
        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "All Picasa icons are property of Google, Inc.");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jToolBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 865, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(504, Short.MAX_VALUE)
                .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 228, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(27, 27, 27)
                .add(jLabel4)
                .add(21, 21, 21))
            .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 865, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jSplitPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 459, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel4)
                    .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(189, 189, 189))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void PreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PreviousActionPerformed
        // TODO add your handling code here:
        int row =jTree1.getSelectionRows()[0];
        DefaultMutableTreeNode currentSibling = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
        DefaultMutableTreeNode previousNode = currentSibling.getPreviousSibling();
        if(previousNode!=null){
            checkButtons(previousNode);
            jTree1.setSelectionRow(row - 1);
        }
    }//GEN-LAST:event_PreviousActionPerformed

    private void NextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NextActionPerformed
        // TODO add your handling code here:
        int row =jTree1.getSelectionRows()[0];
        TreeNode firstChild = null;
        if(row<=jTree1.getRowCount()){
        DefaultMutableTreeNode currentSibling = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
        DefaultMutableTreeNode nextNode = currentSibling.getNextSibling();
        if(nextNode!=null){
            checkButtons(nextNode);
            jTree1.setSelectionRow(row + 1);
        }
    }
    }//GEN-LAST:event_NextActionPerformed

    private void PlaySlideShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PlaySlideShowActionPerformed
        // TODO add your handling code here:
        if(ssThread==null){
            jSplitPane1.setDividerLocation(1);
            jScrollPane1.setVisible(false);
            PlaySlideShow.setEnabled(false);
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
            ssThread = new SlideShowThread(this,currentNode);
            ssThread.start();
            Stop.setEnabled(true);
        }
    }//GEN-LAST:event_PlaySlideShowActionPerformed

    private void StopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StopActionPerformed
        // TODO add your handling code here:
        if(ssThread!=null){
            ssThread.stop();
            PlaySlideShow.setEnabled(true);
            Stop.setEnabled(false);
            ssThread = null;
            jScrollPane1.setVisible(true);
            jSplitPane1.setDividerLocation(120);
        }
    }//GEN-LAST:event_StopActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
            UserAuthentication();
            if(authenticateflag==true)
                jButton2.setEnabled(true);
    }//GEN-LAST:event_jButton1ActionPerformed
    private void jPasswordField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyTyped
        // TODO add your handling code here:
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
            UserAuthentication();
        }
    }//GEN-LAST:event_jPasswordField1KeyTyped

    private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyPressed
        // TODO add your handling code here:
                if(evt.getKeyCode()==KeyEvent.VK_ENTER){
                    UserAuthentication();
                    if(authenticateflag==true)
                        jButton2.setEnabled(true);
        }
    }//GEN-LAST:event_jPasswordField1KeyPressed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        Previous.setEnabled(false);
        Next.setEnabled(false);
        PlaySlideShow.setEnabled(false);
        ssThread = null;
        jTree1.setVisible(false);
        jTextPane1.setText("");
        jPanel2.setVisible(true);
        jButton2.setEnabled(false);
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Next;
    javax.swing.JButton PlaySlideShow;
    private javax.swing.JButton Previous;
    protected javax.swing.JButton Stop;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPasswordField jPasswordField1;
    javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized PicasaAlbumTopComponent getDefault() {
        if (instance == null) {
            instance = new PicasaAlbumTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the PicasaAlbumTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized PicasaAlbumTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(PicasaAlbumTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof PicasaAlbumTopComponent) {
            return (PicasaAlbumTopComponent) win;
        }
        Logger.getLogger(PicasaAlbumTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
    // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
    // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return PicasaAlbumTopComponent.getDefault();
        }
    }

    public void valueChanged(TreeSelectionEvent e) {
        displayProcess();
    }


     void showAlbumDetails(Album album) {
        try {
            doc = jTextPane1.getStyledDocument();
            Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
            Style alignment = doc.addStyle("alignment", def);
            StyleConstants.setAlignment(alignment, StyleConstants.ALIGN_LEFT);
            Style bold = doc.addStyle("bold", def);
            
            StyleConstants.setBold(bold, true);
            String url = album.getAlbumEntry().getHtmlLink().getHref();
            Style regularBlue = doc.addStyle("regularBlue", def);
            StyleConstants.setForeground(regularBlue, Color.DARK_GRAY);
            StyleConstants.setUnderline(regularBlue,true);
            regularBlue.addAttribute(LINK_ATTRIBUTE,new URLLinkAction(url));
            
            doc.insertString(doc.getLength(),"\nAlbumInfo"+"\nAlbum Name : "+album.AlbumName+"\nAccess : "+album.getAlbumEntry().getAccess()
                    +"\nLocation : "+album.getAlbumEntry().getLocation()+"\nOwner : "+album.getAlbumEntry().getUsername()+"\nDate : "+album.getAlbumEntry().getDate().toString(),doc.getStyle("bold"));
            doc.insertString(doc.getLength(), "\nLink : "+url,doc.getStyle("regularBlue"));
        } catch (ServiceException ex) {
            Exceptions.printStackTrace(ex);
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    void showImage(File imageFile) {
            ImageIcon albumIcon = new ImageIcon(imageFile.getAbsolutePath()); //createImageIcon("pig.jpg", "a cute...");
            jTextPane1.setText("");
            jTextPane1.insertIcon(albumIcon);
            jTextPane1.setVisible(true);
    }
    	private class TextClickListener extends MouseAdapter {
        @Override
    	    public void mouseClicked( MouseEvent e ) {
    		try{
		        Element elem = doc.getCharacterElement(jTextPane1.viewToModel(e.getPoint()));
    			AttributeSet as = elem.getAttributes();
    			URLLinkAction fla = (URLLinkAction)as.getAttribute(LINK_ATTRIBUTE);
   			if(fla != null)
    			    fla.execute();
    		}
    		catch(Exception x) {
    			x.printStackTrace();
    		}
           }
   	}
 
 
	private class TextMotionListener extends MouseInputAdapter {
        @Override
		public void mouseMoved(MouseEvent e) {
                    try{
                    if(doc.getCharacterElement( jTextPane1.viewToModel(e.getPoint()))!=null){
			Element elem = doc.getCharacterElement( jTextPane1.viewToModel(e.getPoint()));
			AttributeSet as = elem.getAttributes();
			if(StyleConstants.isUnderline(as))
				jTextPane1.setCursor(new Cursor(Cursor.HAND_CURSOR));
			else
				jTextPane1.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    }else{
                    }
                    }
                    catch(NullPointerException ex){
                    }
		}
	}

    
    public void treeExpanded(TreeExpansionEvent event) {
        
    }

    public void treeCollapsed(TreeExpansionEvent event) {
        
    }
    private class URLLinkAction extends AbstractAction{
        private String url;
        URLLinkAction(String bac){
            url=bac;
	}
 	protected void execute() {
         try {
             String osName = System.getProperty("os.name").toLowerCase();
             Runtime rt = Runtime.getRuntime();
	     if (osName.indexOf( "win" ) >= 0) {
		rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
		}
                else if (osName.indexOf("mac") >= 0) {
		rt.exec( "open " + url);
             }		        
	 else if (osName.indexOf("ix") >=0 || osName.indexOf("ux") >=0 || osName.indexOf("sun") >=0) {
       	        String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
	        			"netscape","opera","links","lynx"};
      	        // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
       	        StringBuffer cmd = new StringBuffer();
       	        for (int i = 0 ; i < browsers.length ; i++)
	        cmd.append((i == 0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
       	        rt.exec(new String[] { "sh", "-c", cmd.toString() });
                }
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
		}
    	 }
 	public void actionPerformed(ActionEvent e){
         execute();
    }
	}
}